package edu.controller;

import edu.service.UserRoleService;
import edu.vo.UserRole;
import edu.vo.ID.UserRoleId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/user-roles")
public class UserRoleController {

    @Autowired
    private UserRoleService userRoleService;

    /**
     * 保存用户角色关联信息
     * @param userRole 用户角色关联对象
     * @return 保存后的用户角色关联对象
     */
    @PostMapping
    public ResponseEntity<UserRole> saveUserRole(@RequestBody UserRole userRole) {
        UserRole savedUserRole = userRoleService.saveUserRole(userRole);
        return new ResponseEntity<>(savedUserRole, HttpStatus.CREATED);
    }

    /**
     * 根据ID获取用户角色关联信息
     * @param id 用户角色关联ID
     * @return 用户角色关联对象的Optional包装
     */
    @GetMapping("/{id}")
    public ResponseEntity<UserRole> getUserRoleById(@PathVariable UserRoleId id) {
        Optional<UserRole> userRoleOptional = userRoleService.getUserRoleById(id);
        return userRoleOptional.map(userRole -> new ResponseEntity<>(userRole, HttpStatus.OK))
                .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 获取所有用户角色关联信息
     * @return 用户角色关联列表
     */
    @GetMapping
    public ResponseEntity<List<UserRole>> getAllUserRoles() {
        List<UserRole> userRoles = userRoleService.getAllUserRoles();
        return new ResponseEntity<>(userRoles, HttpStatus.OK);
    }

    /**
     * 根据ID删除用户角色关联信息
     * @param id 用户角色关联ID
     * @return 无内容响应
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUserRoleById(@PathVariable UserRoleId id) {
        userRoleService.deleteUserRoleById(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 更新用户角色关联信息
     * @param id 用户角色关联ID
     * @param userRole 新的用户角色关联信息
     * @return 更新后的用户角色关联对象
     */
    @PutMapping("/{id}")
    public ResponseEntity<UserRole> updateUserRole(@PathVariable UserRoleId id, @RequestBody UserRole userRole) {
        UserRole updatedUserRole = userRoleService.updateUserRole(id, userRole);
        return updatedUserRole != null ? new ResponseEntity<>(updatedUserRole, HttpStatus.OK)
                : new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}